﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.Unity;

namespace Web.Utility
{
    public class UnityDependencyResolver : IDependencyResolver
    {
        public IUnityContainer unityContainer;

        public UnityDependencyResolver()
        {
            unityContainer = new UnityContainer().AddNewExtension<EnterpriseLibraryCoreExtension>();
      

            // Configure container
            UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
            section.Configure(unityContainer);



            // Cache current unity configuration
            unityContainer.RegisterInstance<IUnityContainer>(unityContainer); 
        }

        public object GetService(Type serviceType)
        {
            try
            {
               
                return unityContainer.Resolve(serviceType);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return unityContainer.ResolveAll(serviceType);
        }
    }
    public class ControllerActivator : IControllerActivator
    {

        public IController Create(RequestContext requestContext, Type controllerType)
        {
            return DependencyResolver.Current.GetService(controllerType) as IController;
        }
    }

    public class ViewPageActivator : IViewPageActivator
    {

        public object Create(ControllerContext controllerContext, Type type)
        {
            return DependencyResolver.Current.GetService(type);
        }
    }
}